package fun.tan90.easy.binlog.plugin.redis.single.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.redis.single.listener.RedisSingleEventProcessor;
import fun.tan90.easy.binlog.plugin.redis.single.service.impl.RedisSinglePluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class RedisSinglePluginAutoConfiguration {

    public RedisSinglePluginAutoConfiguration() {
        log.info("init RedisSinglePlugin");
    }

    @Bean
    public RedisSingleCacheLoader redisPoolCacheLoader() {
        return new RedisSingleCacheLoader();
    }

    @Bean
    public LoadingCache<String, JedisPool> redisSinglePoolCache(RedisSingleCacheLoader redisSingleCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.REDIS_SINGLE.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(redisSingleCacheLoader);
    }

    @Bean
    public RedisSingleEventProcessor redisSingleEventProcessor(LoadingCache<String, JedisPool> redisSinglePoolCache) {
        return new RedisSingleEventProcessor(redisSinglePoolCache);
    }

    @Bean(name = "redis-single")
    public PluginService redisSinglePluginService() {
        return new RedisSinglePluginService();
    }
}